<template>
  <div style="width: 80%;margin: 0 auto " >
    <a-table :dataSource="recipes" :columns="columns" :rowKey="record => record.recipe_id" >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'image_url'" >
          <a-image :src="record.image_url" style="width: 60%"></a-image>
        </template>
        <template v-if="column.key === 'operation'">
          <a-space>
            <a-popconfirm
                title="删除后不可恢复，确认删除？"
                @confirm="onDelete(record)"
                ok-text="确认"
                cancel-text="取消"
            >
              <a-button type="dashed">删除</a-button>
            </a-popconfirm>
            <a-button type="default" @click="onEdit(record)">编辑</a-button>
          </a-space>
        </template>
      </template>
    </a-table>
    <a-modal v-model:open="open" title="食谱" @ok="handleSubmit" ok-text="确认" cancel-text="取消">
      <a-form :model="currentRecipe" :label-col="{ span: 4 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="食谱名">
          <a-input v-model:value="currentRecipe.title" />
        </a-form-item>
        <a-form-item label="食谱描述">
          <a-input v-model:value="currentRecipe.description" />
        </a-form-item>
        <a-form-item label="食材列表">
            <a-input v-model:value="currentRecipe.ingredients" />
        </a-form-item>
        <a-form-item label="制作步骤">
            <a-input v-model:value="currentRecipe.instructions" />
        </a-form-item>
        <a-form-item label="食谱图片">
          <a-input v-model:value="currentRecipe.image_url" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue';
import axios from 'axios';
import {notification} from 'ant-design-vue';

// 定义学生数据列表
const recipes = ref([]);
const open = ref(false);
const currentRecipe = ref({});

// 定义表格列
const columns = [
  {
    title: 'RecipeID',
    dataIndex: 'recipe_id',
    key: 'recipe_id',
  },
  {
    title: '食谱名',
    dataIndex: 'title',
    key: 'title',
  },
  {
    title: '食谱描述',
    dataIndex: 'description',
    key: 'description',
  },
  {
    title: '食材列表',
    dataIndex: 'ingredients',
    key: 'ingredients',
  },
  {
    title: '制作步骤',
    dataIndex: 'instructions',
    key: 'instructions',
  },
  {
    title: '食谱图片',
    dataIndex: 'image_url',
    key: 'image_url',
  },
  {
    title: '发布者',
    dataIndex: 'user_id',
    key: 'user_id',
  },
  // {
  //   title: '创建时间',
  //   dataIndex: 'create_at',
  //   key: 'create_at',
  // },
  // {
  //   title: '更新时间',
  //   dataIndex: 'updated_at',
  //   key: 'updated_at',
  // },
  {
    title: '操作',
    key: 'operation',
  },
];

// 编辑
const onEdit = (record) => {
  currentRecipe.value = {...record};
  open.value = true;
};

// 删除
const onDelete = (record) => {
  const token = localStorage.getItem('Token');

  // 如果存在token，则设置请求头
  const config = {
    headers: {
      'Token': token
    }
  };
  // console.log(token)
  // console.log(config)
  axios.delete(`/recipe?recipeId=${record.recipe_id}`,config)
      .then((response) => {
        const data = response.data;
        if (data.code === 0) {
          handleFetchRecipes();
          notification.success({description: "删除成功！"});
        } else {
          notification.error({description: data.message});
        }
      })
      .catch((error) => {
        console.error('Delete error:', error);
        notification.error({description: '删除失败'});
      });
};

// 提交表单
const handleSubmit = () => {
  console.log("currentRecipe.value:",currentRecipe.value)
  axios.put("/recipe/"+currentRecipe.value.recipe_id, currentRecipe.value).then((response) => {
    let data = response.data;
    console.log(data)
    if (data.code == 0) {
      notification.success({description: "保存成功"});
      console.log('Current Recipe:', currentRecipe.value);
      handleFetchRecipes();
      open.value = false;
    } else {
      notification.error({description: data.message})
    }
  });
};

// 获取学生数据
const handleFetchRecipes = () => {
  const token = localStorage.getItem('Token');

  // 如果存在token，则设置请求头
  const config = {
    headers: {
      'Token': token
    }
  };
  // console.log(token)
  // console.log(config)
  axios.get('/recipe/lists',config)
      .then((response) => {
        const data = response.data;
        if (data.code === 0) {
          recipes.value = data.data;
          // console.log(data);
        } else {
          notification.error({description: data.message});
        }
      })
      .catch((error) => {
        // console.error('没有得到数据:', error);
        notification.error({description: '没有得到数据'+error});
      });
};

// 在组件挂载时加载数据
onMounted(() => {
  handleFetchRecipes();
});
</script>

<style scoped>

</style>